<template>
  <div class="h-full flex flex-col">
    <!-- 对话标题栏 -->
    <div
      class="flex justify-between items-center h-[40px] px-6 border-b border-gray-200 bg-white shadow-sm"
    >
      <h2 class="text-lg font-medium text-gray-800 truncate max-w-[70%]">
        {{ converSation?.title || '未命名对话' }}
      </h2>
      <p class="text-sm text-gray-500">{{ dayjs(converSation?.updateAt).format('YYYY-MM-DD') }}</p>
    </div>

    <!-- 消息列表区域 -->
    <div class="flex-1 overflow-hidden">
      <MessageList :messages="filterMessages" @finishRender="handleFinishRender" />
    </div>

    <!-- 消息输入区域 -->
    <div class="min-h-[60px] mt-2 flex items-end">
      <MessageInput @sendMessage="handleMessage" :disabled="inputDisabled" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue'
  import MessageInput from '../components/MessageInput.vue'
  import MessageList from '../components/MessageList.vue'
  import dayjs from 'dayjs'
  import { useRoute } from 'vue-router'
  import type {
    MessageListProps,
    ConversationProps,
    StartChatProps,
    updateMessageProps,
    MessageContent
  } from '../type'
  import { db } from '../db'

  // ===== 状态变量 =====
  const route = useRoute()
  const inputDisabled = ref(false)
  const messages = ref<MessageListProps[]>([])
  const converSations = ref<ConversationProps[]>([])
  const conversationId = ref<number>(Number(route.query.id as string))
  let lastMessage = ''
  let lastMessageId: number | undefined
  let lastImage: string | undefined

  // ===== 计算属性 =====
  const filterMessages = computed(() => {
    if (!conversationId.value) return []
    return messages.value.filter(item => item.conversationid === conversationId.value)
  })

  const converSation = computed(() => {
    return converSations.value.find(item => item.id === conversationId.value)
  })

  // ===== 监听器 =====
  // 监听路由变化
  watch(
    () => route.query.id,
    async newValue => {
      conversationId.value = Number(newValue)
      converSations.value = await db.conversations.where({ id: conversationId.value }).toArray()
    }
  )

  // 监听消息状态变化，控制输入框禁用状态
  watch(
    filterMessages,
    () => {
      let flag = false
      filterMessages.value.forEach(item => {
        if (item.state === 'stream') {
          flag = true
        }
      })
      inputDisabled.value = flag
    },
    {
      immediate: true
    }
  )

  // ===== 方法 =====
  // 获取对话列表
  const getConversations = async () => {
    converSations.value = await db.conversations.toArray()
  }

  // 处理初始化逻辑
  const isInitHandler = async () => {
    // 获取最后一条消息
    if (conversationId.value) {
      const last = await db.messages.where({ conversationid: conversationId.value }).last()

      if (last) {
        lastMessage = last.message.content
        lastImage = last.image
      }
    }

    // 如果是初始化新对话，创建一条加载中的消息
    const initId = route.query?.init
    if (initId) {
      const createData: Omit<MessageListProps, 'id'> = {
        message: {
          role: 'user',
          content: ''
        },
        type: 'answer',
        state: 'loading',
        conversationid: conversationId.value,
        createAt: new Date().toISOString(),
        updateAt: new Date().toISOString()
      }
      const messageId = await db.messages.add(createData)
      lastMessageId = messageId
      messages.value.push({
        id: messageId,
        ...createData
      })
    }
  }

  // 获取消息并启动聊天
  const getMessages = async () => {
    // 获取所有消息
    messages.value = await db.messages.toArray()

    // 确保对话数据已加载
    if (!converSation.value) {
      console.warn('对话数据尚未加载完成')
      return
    }

    // 获取提供者信息
    const provider = await db.providers.where({ id: converSation.value.providerid }).first()

    // 只有在有 lastMessageId 时才启动聊天和禁用输入
    if (lastMessageId) {
      // 准备聊天数据
      const data: StartChatProps = {
        messageId: lastMessageId as number,
        message: {
          role: 'user',
          content: lastMessage,
          ...(lastImage ? { image: lastImage } : {})
        },
        providerName: provider?.name || '',
        selectModel: converSation.value.selectModel
      }

      inputDisabled.value = true

      window.electronApi.startChat(data)
    } else {
      // 如果没有待处理的消息，确保输入框是启用的
      inputDisabled.value = false
    }
  }

  // 设置消息更新监听器
  const onUpdateMessage = async () => {
    window.electronApi.onUpdateMessage(async (data: updateMessageProps) => {
      const { is_end, result, messageId } = data
      const update = await db.messages.where({ id: messageId }).first()

      if (update) {
        // 更新消息内容
        const updateData: Omit<MessageListProps, 'id'> = {
          ...update,
          message: {
            role: 'assistant',
            content: update.message.content + result
          },
          state: is_end ? 'finish' : 'stream',
          updateAt: new Date().toISOString()
        }

        // 更新数据库
        await db.messages.update(messageId, updateData)

        // 更新本地状态
        const index = messages.value.findIndex(item => item.id === messageId)
        if (index !== -1) {
          messages.value[index] = {
            ...messages.value[index],
            ...updateData
          }
        }
      }
    })
  }

  // 处理发送消息
  const handleMessage = async (message: string, base64: string, name: string) => {
    const date = new Date()
    let image: string | undefined

    if (base64 && name) {
      image = await window.electronApi.copyImage({
        data: base64,
        name
      })
    }
    // 创建用户问题消息
    const createData: Omit<MessageListProps, 'id'> = {
      message: {
        role: 'user',
        content: message
      },
      type: 'question',
      conversationid: conversationId.value,
      createAt: date.toISOString(),
      updateAt: date.toISOString(),
      ...(image ? { image } : {})
    }
    await db.messages.add(createData)
    messages.value = await db.messages.toArray()

    // 准备历史消息数据
    const messageData: MessageContent[] = filterMessages.value
      .filter(item => item.state !== 'loading')
      .map(item => {
        return {
          role: item.type === 'question' ? 'user' : 'assistant',
          content: item.message.content,
          ...(item.image ? { image: item.image } : {})
        }
      })

    // 创建AI回答的加载状态消息
    const newMessageId = await db.messages.add({
      message: {
        role: 'assistant',
        content: ''
      },
      type: 'answer',
      state: 'loading',
      conversationid: conversationId.value,
      createAt: date.toISOString(),
      updateAt: date.toISOString()
    })
    messages.value = await db.messages.toArray()

    // 获取提供者信息
    const provider = await db.providers.where({ id: converSation.value!.providerid }).first()

    // 准备聊天数据并发送
    const data: StartChatProps = {
      messageId: newMessageId,
      message: messageData,
      providerName: provider!.name,
      selectModel: converSation.value!.selectModel
    }
    inputDisabled.value = true

    window.electronApi.startChat(data)
    await onUpdateMessage()
  }

  // 处理消息渲染完成事件
  const handleFinishRender = () => {
    // 可以在这里添加渲染完成后的逻辑
  }

  // ===== 生命周期钩子 =====
  onMounted(async () => {
    // 按顺序执行初始化操作
    await getConversations() // 先获取对话列表
    await isInitHandler() // 然后处理初始化
    await getMessages() // 最后获取消息
    await onUpdateMessage() // 设置消息更新监听器
  })
</script>
